package com.leantech.android.browser.ui.favorites.vm


import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.cscj.android.repository.db.entity.BrowseHistoryEntity
import com.cscj.android.repository.repo.history.BrowserHistoryRepository
import com.cscj.android.utils.formatHumanReadableDay
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject

class BrowserHistoryViewModel : ViewModel(), KoinComponent {

    private val browserHistoryRepository by inject<BrowserHistoryRepository>()

    val historyEditMode: MutableStateFlow<FavoritesViewModel.EditMode> = MutableStateFlow(
        FavoritesViewModel.EditMode.Off
    )


    private val _historySearchKeywordFlow = MutableStateFlow<String?>(null)

    private val _historyFlow = _historySearchKeywordFlow.flatMapLatest { keyword ->
        browserHistoryRepository.browserHistoryList(keyword)
    }

    @OptIn(ExperimentalCoroutinesApi::class)
    val historyFlow = _historyFlow.map { list ->
            list.groupBy {
                formatHumanReadableDay(it.visitTime.time)
            }.flatMap { (k, v) ->
                val result =  mutableListOf<HistoryItem>()
                result.add(HistoryItem.Title(k))
                result.addAll(v.map {
                    HistoryItem.Item(it)
                })
                result
            }
        }.stateIn(
            viewModelScope,
            SharingStarted.WhileSubscribed(5000),
            emptyList()
        )

    val historyCountFlow = _historyFlow.map {
        it.size
    }

    val selectedHistoryIds = HashSet<Int>()

    fun getAllHistoryId(): Set<Int> {
        return historyFlow.value.mapNotNull {
            if(it is HistoryItem.Item) it.item.id else null
        }.toSet()
    }

    fun isAllSelected(): Boolean{
        return getAllHistoryId().size == selectedHistoryIds.size && selectedHistoryIds.isNotEmpty()
    }


    fun searchHistory(keyword: String?) {
        viewModelScope.launch {
            _historySearchKeywordFlow.emit(keyword)
        }
    }

    fun deleteHistory() {
        viewModelScope.launch {
            browserHistoryRepository.deleteByIds(selectedHistoryIds.toIntArray())
        }
    }

    fun toggleHistoryEditMode() {
        historyEditMode.update {
            if (it == FavoritesViewModel.EditMode.On) {
                FavoritesViewModel.EditMode.Off
            } else {
                FavoritesViewModel.EditMode.On
            }
        }
    }

    sealed interface HistoryItem {
        data class Title(val title: String) : HistoryItem

        data class Item(val item: BrowseHistoryEntity) : HistoryItem
    }

}